﻿using CIS.DB;
using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CIS.Web.Controllers
{
	[AllowAnonymous]
	[RoutePrefix("MeetingFeedback")]
	public class MeetingFeedbackController : BaseDbController
	{
		[Route("Index/{ConferenceId}/{QuizId}/{AttendenceId}")]
		public async Task<ActionResult> Index(string conferenceId, string quizId, string attendenceId)
		{
			var quizMaster = await DbContext.QuizMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ConferenceId == conferenceId &&
						x.ID == quizId);
			if (quizMaster == null)
			{
				return RedirectToAction(nameof(HomeController.MainIndex), nameof(HomeController).GetControllerName());
			}

			var model = new MeetingFeedbackModel();

			model.QuizId = quizId;
			model.ConferenceId = conferenceId;
			model.AttendenceId = attendenceId;
			model.QuizName = quizMaster.QuizName;

			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", conferenceId);

			return View(model);
		}

		[Route("Index/{ConferenceId}/{QuizId}")]
		public async Task<JsonCamelCaseResult> GetData(MeetingFeedbackModel model)
		{
			var sql = from quizMaster in DbContext.QuizMaster.AsNoTracking()
						.Where(x => x.Status == ConstValues.Status.正常 &&
							x.ConferenceId == model.ConferenceId &&
							x.ID == model.QuizId)
				  join questionMaster in DbContext.QuestionMaster.AsNoTracking()
						.Where(x => x.Status == ConstValues.Status.正常)
					  on quizMaster.ID equals questionMaster.QuizId
				  join answerMaster in DbContext.AnswerMaster.AsNoTracking()
						.Where(x => x.Status == ConstValues.Status.正常)
					  on questionMaster.ID equals answerMaster.QuestionId into answers
				  from answer in answers.DefaultIfEmpty()
				  orderby questionMaster.QuestionType, questionMaster.Sort, answer.Sort
				  select new QuizQuestionAnswerModel
				  {
					  QuizName = quizMaster.QuizName,
					  QuestionId = questionMaster.ID,
					  QuestionType = questionMaster.QuestionType,
					  QuestionName = questionMaster.QuestionName,
					  AnswerId = answer.ID,
					  Answer = answer.Answer,
				  };

			int total = await sql.CountAsync();

			var sqlResult = await sql.ToListAsync();

			return JsonCamelCase(new
			{
				Total = total,
				Rows = sqlResult,
			},
			JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("Submit")]
		public async Task<JsonResult> Submit(MeetingFeedbackModel model)
		{
			using (var transaction = DbContext.Database.BeginTransaction())
			{
				var conferenceAttendenceInfo = await DbContext.ConferenceAttendenceInfo.AsNoTracking()
						.FirstOrDefaultAsync(x => x.ID == model.AttendenceId);

				var user = await DbContext.SysUserMaster.AsNoTracking()
						.FirstOrDefaultAsync(x => x.Mail == conferenceAttendenceInfo.Mail);

				var now = DateTime.Now;
				if (user != null)
				{
					var result = await DbContext.ProfileQuizInfo
							.FirstOrDefaultAsync(x => x.UserName == user.UserName &&
								x.QuizId == model.QuizId);
					result.Status = ConstValues.ReplyStatus.已回复;
					result.Updater = user.UserName;
					result.UpdateDate = now;

					if (model.FeedbackList != null)
					{
						var exist = await DbContext.FeedbackInfo
							.Where(x => x.ConferenceId == model.ConferenceId &&
								x.QuizId == model.QuizId &&
								x.Creator == user.UserName)
							.ToListAsync();

						if (exist.Count > 0)
						{
							DbContext.FeedbackInfo.RemoveRange(exist);
						}
					}
				}

				if (model.FeedbackList != null)
				{
					foreach (var feedback in model.FeedbackList)
					{
						var feedbackInfo = new FeedbackInfo
						{
							ID = Utility.GetTableId(ConstValues.TableName.FeedbackInfo),
							ConferenceId = model.ConferenceId,
							QuizId = model.QuizId,
							QuestionId = feedback.QuestionId,
							Feedback = feedback.Feedback,
							Status = ConstValues.Status.正常,
							Creator = user != null ? user.UserName : ConstValues.DefaultUser,
							CreateIP = Utility.GetRealIP(),
							CreateDate = now
						};
						DbContext.FeedbackInfo.Add(feedbackInfo);
					}
				}

				await DbContext.SaveChangesAsync();
				transaction.Commit();

				string controller = RouteData.Values["controller"].ToString();
				string actionName = RouteData.Values["action"].ToString();
				Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", conferenceAttendenceInfo.ConferenceId);
			}

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
					JsonRequestBehavior.AllowGet);
		}
	}
}